import imaplib
import email
from email.header import decode_header
from email.utils import parsedate_to_datetime
import traceback
import pytz

EMAIL = 'QQ@qq.com'
AUTH_CODE = ''
IMAP_SERVER = 'imap.qq.com'
PORT = 993

def get_latest_email():
    try:
        mail = imaplib.IMAP4_SSL(IMAP_SERVER, PORT)
        mail.login(EMAIL, AUTH_CODE)
        mail.select('INBOX')
        status, messages = mail.search(None, 'ALL')
        if status != 'OK':
            print("未找到邮件")
            return
        message_ids = messages[0].split()
        latest_email_id = message_ids[-1]
        status, data = mail.fetch(latest_email_id, '(RFC822)')
        if status != 'OK':
            print("获取邮件失败")
            return

        raw_email = data[0][1]
        msg = email.message_from_bytes(raw_email)
        email_info = {
            'subject': decode_header(msg['Subject'])[0][0].decode(),
            'from': decode_header(msg['From'])[0][0],
            'date': parsedate_to_datetime(msg['Date']),
            'body': ''
        }
        for part in msg.walk():
            content_type = part.get_content_type()
            if content_type == 'text/plain':
                body = part.get_payload(decode=True).decode()
                email_info['body'] = body.strip()
                break
        if email_info['date']:
            cst_timezone = pytz.timezone('Asia/Shanghai')
            email_info['date'] = email_info['date'].astimezone(cst_timezone).strftime('%Y-%m-%d %H:%M:%S')
        return email_info
    except Exception as e:
        print(f"发生错误: {e}")
        print(traceback.format_exc())
    finally:
        if 'mail' in locals():
            mail.logout()

if __name__ == '__main__':
    latest_email = get_latest_email()
    if latest_email:
        print("主题:", latest_email['subject'])
        print("发件人:", latest_email['from'])
        print("时间:", latest_email['date'])
        print("正文:", latest_email['body'][:170])
